package com.lib.updater;

import android.app.DownloadManager;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

public class DownloadContentObserver extends ContentObserver {

    private Updater.UpdateListener updateListener;
    private Context mContext;
    private long lastTime;
    private long downloadId;

    public DownloadContentObserver(Context context) {
        super(new Handler(Updater.getLooper()));
        mContext = context;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Log.d("ttt", "onChange");
        if (System.currentTimeMillis() - lastTime > 1000) {
            final long[] status = getBytesAndStatus(downloadId);
            if (updateListener != null) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        updateListener.process(status[0], status[1]);
                    }
                });
            }
            lastTime = System.currentTimeMillis();
        }
    }

    private long[] getBytesAndStatus(long downloadId) {
        long[] bytesAndStatus = new
                long[]{-1, -1, 0};
        DownloadManager.Query query = new
                DownloadManager.Query().setFilterById(downloadId);
        Cursor cursor = null;
        try {
            cursor = Downloader.getInstance().getDM(mContext).query(query);
            if
            (cursor != null && cursor.moveToFirst()) {
                //已经下载文件大小
                bytesAndStatus[0] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //下载文件的总大小
                bytesAndStatus[1] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //下载状态
                bytesAndStatus[2] = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return bytesAndStatus;
    }

    public void setUpdateListener(Updater.UpdateListener listener) {
        updateListener = listener;
    }

    public void setDownloadId(long downloadId) {
        this.downloadId = downloadId;
    }
}
